from django.db import models
import base64
from django.core.validators import FileExtensionValidator
from django.core.files.uploadedfile import InMemoryUploadedFile
import io

class NavigationGroup(models.Model):
    """导航分组"""
    title = models.CharField('分组名称', max_length=100)
    order = models.IntegerField('排序', default=0)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '导航分组'
        verbose_name_plural = verbose_name
        ordering = ['order', 'id']

    def __str__(self):
        return self.title

class NavigationLink(models.Model):
    """导航链接"""
    # 图标选项已经移到admin.py中，这里不再定义
    
    group = models.ForeignKey(NavigationGroup, verbose_name='所属分组', on_delete=models.CASCADE, related_name='links')
    name = models.CharField('名称', max_length=50)
    url = models.URLField('链接地址')
    icon = models.CharField('Font Awesome图标', max_length=50, blank=True)
    icon_image_base64 = models.TextField('自定义图标(Base64)', blank=True, null=True, help_text='图片将以Base64格式存储')
    icon_image_type = models.CharField('图片类型', max_length=30, blank=True, null=True)
    description = models.CharField('描述', max_length=200, blank=True)
    order = models.IntegerField('排序', default=0)
    is_active = models.BooleanField('是否启用', default=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '导航链接'
        verbose_name_plural = verbose_name
        ordering = ['order', 'id']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        # 如果有临时上传的图片文件，转换为base64存储
        if hasattr(self, '_icon_image_temp') and self._icon_image_temp:
            image = self._icon_image_temp
            if isinstance(image, InMemoryUploadedFile):
                # 读取图片内容
                image_data = image.read()
                # 转换为base64
                base64_data = base64.b64encode(image_data).decode('utf-8')
                # 存储base64数据和文件类型
                self.icon_image_base64 = base64_data
                self.icon_image_type = image.content_type
            delattr(self, '_icon_image_temp')
        super().save(*args, **kwargs)

    @property
    def icon_image_data(self):
        """获取图片的data URL格式"""
        if self.icon_image_base64 and self.icon_image_type:
            return f'data:{self.icon_image_type};base64,{self.icon_image_base64}'
        return None
